/** * 公共组件->导入弹窗 */
<template>
  <div>
    <Modal v-model="showModal" width="600" @on-cancel="cancel" :title="titleText">
      <div class="hised">
        <div class="impright">
          <p class="mb10">导入说明</p>
          <p class="mb10">1、表头需和客户字段一致。</p>
          <p class="mb10">2、文件格式选择{{ fileType.join("、") }}</p>
          <p>3、导入的文件不超过1万条数据。</p>
        </div>
        <div v-if="downloadTempUrl">
          <Button @click="downloadTemp" :loading="downLoading">下载模板</Button>
        </div>
      </div>
      <div class="contd">
        <Upload
          refs="upload"
          :action="uploadUrl"
          :headers="{
              token: token,
            }"
          :data="data"
          type="drag"
          :on-format-error="handleFormatError"
          :before-upload="beforeUpload"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :accept="fileType.map(v => {return '.' + v}).join(',')"
          :show-upload-list="false"
          :on-progress="onprogress"
          style="height: 480px">
          <div style="margin-top: 149px;">
            <div>
              <img src="../../assets/img/upload.svg" alt=""/>
            </div>
            <div class="texc">
              <span> 将文件拖拽到此区域 支持{{ fileType.join("、") }}格式</span>
            </div>
            <div class="mt20">
              <Button :loading="loading" size="large">选择上传文件</Button>
            </div>
          </div>
        </Upload>
      </div>
      <div slot="footer"></div>
      <Spin fix v-if="loading">
        <Icon type="load-c" size=18 class="demo-spin-icon-load"></Icon>
        <div>数据导入{{ percent }}%...</div>
      </Spin>
    </Modal>
  </div>
</template>
<script>
import axios from "axios";
import {base} from "@/libs/axios";

export default {
  props: {
    importModal: {
      type: Boolean,
      default: false
    },
    titleText: {
      type: String,
      default: "导入数据"
    },
    // 下载模板接口
    downloadTempUrl: {
      type: String,
      default: ""
    },
    // 文件上传类型
    fileType: {
      type: Array,
      default: () => {
        return ["xls", "xlsx"]
      }
    },
    // 1-批量导入 2-批量增员 3-批量减员 4-批量享受政策
    importType: {
      type: Number,
      default: 1
    },
    // 文件上传接口
    requestUrl: {
      type: String,
      default: ""
    },
    // 上传参数
    data: {
      type: Object,
      default: () => {
        return {}
      }
    },
  },
  data() {
    return {
      downloadBase: process.env.NODE_ENV === 'production' || process.env.VUE_APP_EVN_CONFIG === 'pro' ? 'https://preshoufei.yzxsaas.com/pc' : 'https://preshoufei.yzxsaas.com/pc',
      token: JSON.parse(window.localStorage.getItem("myData")).token,
      showModal: false,
      loading: false,
      uploadUrl: base + this.requestUrl,
      downLoading: false,
      percent: 0, // 导入进度
      errorData: [],  // 导入错误数据
    };
  },
  watch: {
    importModal: {
      handler(obj) {
        this.showModal = obj;
        if (obj) {
          this.loading = false;
          // this.errorData = [];
          this.percent = 0;
        }
      },
      deep: true,
    },
    requestUrl(val) {
      this.uploadUrl = base + val;
    }
  },
  created() {
  },
  methods: {
    // 文件上传时的钩子
    onprogress() {
      this.loading = true;
    },
    // 下载模板
    downloadTemp() {
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = this.downloadBase + this.downloadTempUrl;
      document.body.appendChild(link);
      link.click();
      /*this.downLoading = true;
      axios({
        headers: {
          "Content-Type": "application/json",
        },
        url: this.downloadTempUrl,
        data: '',
        responseType: "blob",
        method: "post",
      }).then((res) => {
        this.downLoading = false;
        const name = window.decodeURI(
          res.headers["content-disposition"].split("=")[1],
          "UTF-8"
        );
        const blob = new Blob([res.data], {
          type: "application/vnd.ms-excel"
        });
        var url = window.URL.createObjectURL(blob);
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", name);
        document.body.appendChild(link);
        link.click();
      }).catch(err => {
        this.downLoading = false;
      });*/
    },
    cancel() {
      // 隐藏导入弹框
      this.$emit("cancel");
    },
    beforeUpload(file) {
      this.loading = true; //钩子函数返回字段
      let formData = new FormData();
      formData.append("file", file);
      return new Promise((resolve, reject) => {
        axios({
          headers: {
            "Content-Type": "multipart/form-data",
            "token": JSON.parse(window.localStorage.getItem("myData")).token
          },
          url: base + '/data/import/upload/file/' + this.importType,
          data: formData,
          method: "post",
        }).then((res) => {
          let result = res.data;
          if (result.code == 20000) {
            this.uploadUrl = base + this.requestUrl + '/' + result.data.id + '/' + result.data.batchCode;
            resolve();
          } else {
            this.$Message.error(result.message);
            this.loading = false;
            reject();
          }
        }).catch(err => {
          this.$Message.error("数据导入失败！请按照模板类型提交");
          this.loading = false;
          reject();
        })
      })
    },
    // 成功的回调
    uploadSuccess(res, file, fileList) {
      if (res.code === 20000) {
        this.getImportSchedule(res);
      } else {
        this.$Message.error(res.message);
        this.loading = false;
      }
    },
    // 获取导入进度条
    getImportSchedule(params) {
      this.APIS.importSchedule({uuid: params.data}).then((res) => {
        if (res.code == 20000) {
          let data = res.data.split("/");
          let percent = Number(data[0]) / Number(data[1]) * 100;
          this.percent = percent;
          if (percent < 100) {
            this.getImportSchedule(params);
          } else {
            // 获取错误数据
            this.getImportErrorName(params, Number(data[1]));
          }
        } else {
          this.loading = false;
          this.$Message.error(res.message);
        }
      })
    },
    // 因名字原因失败的数据
    getImportErrorName(params, totalNum) {
      this.APIS.importErrorName({uuid: params.data}).then((res) => {
        if (res.code == 20000) {
          if (res.data) {
            this.errorData = res.data;
          }
          this.getImportErrorIdCard(params, totalNum);
        } else {
          this.loading = false;
          this.$Message.error(res.message);
        }
      })
    },
    // 因身份信息原因失败的数据
    getImportErrorIdCard(params, totalNum) {
      this.APIS.importErrorIdCard({uuid: params.data}).then((res) => {
        if (res.code == 20000) {
          if (res.data) {
            this.errorData = this.errorData.concat(res.data);
          }
          this.$Notice.open({
            title: "导入数据",
            desc: "导入成功" + (totalNum - this.errorData.length) + "条，失败" + this.errorData.length + "条",
            duration: 5,  // 0 不自动关闭
            render: h => {
              return h("span", [
                "导入成功" + (totalNum - this.errorData.length) + "条，失败" + this.errorData.length + "条",
                /*h("a", {
                    style: {
                      display: "block",
                      marginTop: "10px",
                    },
                    on: {
                      click: () => {
                      }
                    }
                  },
                  "下载数据"
                )*/
              ])
            }
          })
          this.loading = false;
          this.$emit("success");
        } else {
          this.loading = false;
          this.$Message.error(res.message);
        }
      })
    },
    // 失败的回调
    uploadError(err, file, fileList) {
      this.$Message.error("数据导入失败！请按照模板类型提交");
      this.loading = false;
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: `文件 ${file.name} 格式不正确, 请上传${this.fileType.join("/")}格式文件!`
      })
      this.loading = false;
    },
  },
};

</script>
<style lang="less" scoped>
/deep/ .ivu-modal-header {
  border-bottom: 1px solid #eeeeee;
  padding: 16px 20px;
}

/deep/ .ivu-modal-header-inner {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
  line-height: 22px;
}

/deep/ .ivu-modal-close {
  top: 11px;
}

/deep/ .ivu-upload-drag {
  background: #fff;
}

/deep/ .ivu-btn-text {
  color: #b3b3b3;
}

/deep/ .ivu-modal-body {
  padding: 20px 30px !important;
  //overflow: auto;
  //max-height: 650px;
}

.impright {
  line-height: 20px;
  color: #333333;
}

.hised {
  border: 1px solid #dddddd;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0 auto;
  padding: 16px 20px;
}

.contd {
  border-radius: 4px;
  margin: 10px auto 0 auto;
}

.texc {
  width: 108px;
  line-height: 20px;
  color: #999999;
  margin: 10px auto 0 auto;
}

.filec {
  margin-left: 10px;
  font-size: 14px;
  font-family: Microsoft YaHei;
  color: #404040;

  p {
    color: #000;
  }
}

.buton {
  display: flex;
  justify-content: center;
  margin-top: 150px;
}

/deep/ .ivu-modal-footer {
  border-top: 1px solid #eeeeee;
  padding: 16px 20px;
}

</style>
